package top.revery.task.controller;

import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.revery.api.api.task.ITaskApi;
import top.revery.api.config.UserPageData;
import top.revery.api.entity.payWallet.BaseLogUser;
import top.revery.api.entity.task.BaseCompetePrice;
import top.revery.api.entity.task.BaseLogTask;
import top.revery.api.entity.task.BaseTask;
import top.revery.api.entity.user.BaseUserWorks;
import top.revery.api.entity.vo.BaseTaskUser;
import top.revery.api.entity.user.BaseCompanyUser;
import top.revery.api.entity.user.BaseUserInfo;
import top.revery.api.entity.user.BaseUserKol;
import top.revery.task.dto.*;
import top.revery.task.service.CompeteService;
import top.revery.task.service.TaskService;
import top.revery.task.util.FeignServiceMapping;
import top.revery.task.util.IdUtils;

import java.math.BigDecimal;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author denghao
 * @title
 * @package
 * @date 2019/12/14 9:32
 */
@RestController
//@Transactional
public class TaskController implements ITaskApi {
    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskDto taskDto;
    @Autowired
    private LogTaskDto logTaskDto;
    @Autowired
    private CompetePriceDto competePriceDto;
    @Autowired
    private CompeteService competeService;

     //分页查询
    @Override
    public UserPageData getList(int pageNum, int pageSize, Map map) {

        Page<BaseTask> pageList = taskService.findPage(pageNum, pageSize, map);
        UserPageData userPageData = new UserPageData();
        List<BaseTask> content = pageList.getContent();
        List list = new ArrayList();
        for (BaseTask baseTask : content) {
            BaseCompanyUser company = FeignServiceMapping.taskCompanyService.findById(baseTask.getCompanyId());
            BaseUserKol baseUserKol = FeignServiceMapping.taskKolService.findById(baseTask.getKolId());
            BaseTaskUser baseTaskUser = new BaseTaskUser();
            baseTaskUser.setBaseTask(baseTask);
            baseTaskUser.setBaseCompanyUser(company);
            baseTaskUser.setBaseUserKol(baseUserKol);
            list.add(baseTaskUser);
        }
        userPageData.list = list;
        userPageData.rows = pageList.getTotalElements();
        return userPageData;
    }

    //根据公司的名字模糊查询所有任务
    @Override
    public List<BaseTaskUser> getCompanyName(int pageNum, int pageSize, String companyName) {
        List<BaseCompanyUser> companyUserList = FeignServiceMapping.taskCompanyService.findByName(companyName);
        List<BaseTaskUser> list = new ArrayList();
        for (BaseCompanyUser baseCompanyUser : companyUserList) {
            List<BaseTask> taskList = taskDto.findByCompanyId(baseCompanyUser.getId());
            for (BaseTask baseTask : taskList) {
                BaseTaskUser baseTaskUser = new BaseTaskUser();
                baseTaskUser.setBaseCompanyUser(baseCompanyUser);
                baseTaskUser.setBaseTask(baseTask);
                list.add(baseTaskUser);
            }
        }
        //给集合分页
        List<BaseTaskUser> currentPageList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            int index = (pageNum > 1 ? (pageNum - 1) * pageSize : 0);
            for (int i = 0; i < pageSize && i < list.size() - index; i++) {
                BaseTaskUser data = list.get(index + i);
                currentPageList.add(data);
            }
        }
        return currentPageList;
    }


    //保存任务
    @Override
    @GlobalTransactional
    public BaseTask save(BaseTask baseTask) throws Exception {

        String taskNumber = IdUtils.getTaskNumber();
        BaseTask ta = taskDto.findByTaskNumber(taskNumber);
        baseTask.setTaskNumber(taskNumber);

        if (ta != null) {
            throw new Exception("此任务已存在,请重新填写任务!");
        }
//        Timestamp timestamp = new Timestamp(new Date().getTime());
//        if(baseTask.getTaskTime().before(timestamp)){
//            throw new Exception("期望发布时间不能早于现在时间!");
//        }

        BaseCompanyUser baseCompanyUser = FeignServiceMapping.taskCompanyService.findById(baseTask.getCompanyId());


      return taskDto.save(baseTask);

    }

    //发布任务
    @Override
    public void pubTask(BaseTask baseTask, Long id) throws Exception {

            BaseCompanyUser baseCompanyUser = FeignServiceMapping.taskCompanyService.findById(id);
            BaseUserInfo baseUserInfo = FeignServiceMapping.taskUserService.findById(id).getBaseUserInfo();

            if (baseCompanyUser.getStatus() == 0) {
                throw new Exception("公司还没有审核，暂时不能发布任务！");
            }
            //获取当前时间
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());

            long time1 = timestamp.getTime();

            long time2 = baseCompanyUser.getAddTime().getTime() + (long) 1000 * 3600 * 24 * 30;
            if (time1 > time2) {
                throw new Exception("试用期已过，需充值才能发布任务！");
            }
            if(baseTask.getTaskTime().before(timestamp)){
                throw new Exception("期望发布时间不能早于现在时间!");
            }
            if(baseUserInfo.getTotalMoney().compareTo(baseTask.getTaskMoney())<0){
                       throw new Exception("您的余额已不足,无法发布任务!请充值!");
            }
            String taskNumber;

            BaseTask task1=null;
            if(baseTask.getId()==null){
                task1=null;
            }else {
                Optional<BaseTask> byId = taskDto.findById(baseTask.getId());
                task1=byId.get();
            }
            if (task1 != null && task1.getIsfo() != 0) {
                throw new Exception("此任务已发布存在,请重新填写任务!");
            } else if (task1 != null && task1.getIsfo() == 0) {
                taskNumber = task1.getTaskNumber();
            } else {
                taskNumber = IdUtils.getTaskNumber();
                if (taskDto.findByTaskNumber(taskNumber) != null) {
                    throw new Exception("此任务已发布存在,请重新填写任务!");
                }
            }
            baseTask.setIsfo(1);
            baseTask.setTaskNumber(taskNumber);
            //  baseTask.setTaskTime(new Timestamp(new Date().getTime()));
            taskDto.save(baseTask);
            //获取账户金额
            BigDecimal total = baseUserInfo.getTotalMoney();
            //任务金额
            BigDecimal taskMoney = baseTask.getTaskMoney();
            //设置账户现在金额
            baseUserInfo.setTotalMoney(total.subtract(taskMoney));
            //设置账户冻结金额
            if (baseUserInfo.getFreezingMoney() == null) {
                baseUserInfo.setFreezingMoney(taskMoney);
            }
            baseUserInfo.setFreezingMoney(baseUserInfo.getFreezingMoney().add(taskMoney));
            //  baseUserInfo.setAddTime(new Timestamp(new Date().getTime()));
            //保存
            FeignServiceMapping.taskUserService.save(baseUserInfo);

            //记录发布任务
          /*  BaseLogTask logTask = new BaseLogTask();
            logTask.setTaskNumber(taskNumber);
            logTask.setUserId(baseUserInfo.getId());
            logTask.setTaskName(baseTask.getTaskName());
            logTask.setType(0);
            logTask.setStatus(0);
            logTask.setCurrentMoney("-" + baseTask.getTaskMoney().toString());
            logTask.setOpT(new Timestamp(new Date().getTime()));
            logTaskDto.save(logTask);*/
            BaseLogUser baseLogUser = new BaseLogUser();
            baseLogUser.setMoney(baseTask.getTaskMoney());
            baseLogUser.setUserId(baseUserInfo.getId());
            baseLogUser.setUserType(baseUserInfo.getUserType());
            baseLogUser.setType(3);
            baseLogUser.setEqu("任务冻结的");
            baseLogUser.setAddTime(new Timestamp(new Date().getTime()));
            FeignServiceMapping.logPayUserService.save(baseLogUser);

    }
    //修改任务
    @Override
    public BaseTask updateTask(BaseTask baseTask) throws Exception {

        Optional<BaseTask> task = taskDto.findById(baseTask.getId());

        BaseTask ta = task.get();
        if (ta.getIsfo() == 2) {
            throw new Exception("此任务已被接受,无法修改!");
        }
        //    ta.setTaskType(baseTask.getTaskType());
        ta.setLabel(baseTask.getLabel());
        ta.setTaskMoney(baseTask.getTaskMoney());
        ta.setTaskAsk(baseTask.getTaskAsk());
//        ta.setPubT(new Timestamp(new Date().getTime()));
        return taskDto.save(ta);

    }

    //网红投递任务
    @Override
    public BaseTask deliverTask(BaseTask baseTask, Long id) throws Exception {

        BaseUserKol kol = FeignServiceMapping.taskKolService.findById(id);
        if(kol.getStatus()!=1){
            throw  new Exception("很抱歉!你的审核还未通过!暂时不能投递任务!");
        }
        baseTask.setKolId(id);
        //记录任务投递
        baseTask.setTaskTDTime(new Timestamp(new Date().getTime()));
        return taskDto.save(baseTask);
    }


    //用户接受任务
    @Override
    public void statusTask(Long id, BaseUserInfo baseUserInfo) throws Exception{


            Optional<BaseTask> byId = taskDto.findById(id);

            if (byId.isPresent()) {
                BaseTask baseTask = byId.get();
                baseTask.setStatus(1);
                baseTask.setKolId(baseUserInfo.getId());
                //  baseTask.setTaskTDTime(new Timestamp(new Date().getTime()));
                taskDto.save(baseTask);
            } else {
                throw new Exception("任务不存在!");
            }


    }

 /*   @Override
    public void uploadTaskWorks(BaseTask baseTask, MultipartFile file) throws Exception{
        if (file.isEmpty()) {
            throw new Exception("文件不能为空");
        }
        BaseUserWorks baseUserWorks =new BaseUserWorks();

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();

        if (baseTask.getWorksStatus() == 0) {
            BaseLogTask baseLogTask = new BaseLogTask();
            baseLogTask.setUserId(baseTask.getKolId());
            baseLogTask.setWorksAddress(worksAddress);
            baseLogTask.setOpT(new Timestamp(new Date().getTime()));
            logTaskDto.save(baseLogTask);
            baseTask.setWorksStatus(1);
            baseTask.setWorksNum(logTaskDto.countTaskId(baseTask.getId()));
            taskDto.save(baseTask);
        } else {
            throw new Exception("您的作品已上传，等待企业查收！");
        }

    }*/



    //上传作品
    @Override
    public void uploadTask(BaseTask baseTask, String worksAddress) throws Exception{
            if (baseTask.getWorksStatus() == 0) {
                BaseLogTask baseLogTask = new BaseLogTask();
                baseLogTask.setUserId(baseTask.getKolId());
                baseLogTask.setWorksAddress(worksAddress);
                baseLogTask.setOpT(new Timestamp(new Date().getTime()));
                logTaskDto.save(baseLogTask);
                baseTask.setWorksStatus(1);
                baseTask.setWorksNum(logTaskDto.countTaskId(baseTask.getId()));
                taskDto.save(baseTask);
            } else {
                throw new Exception("您的作品已上传，等待企业查收！");
            }

    }

    //企业是否同意作品
    @Override
    public void isfoGetTask(BaseTask baseTask, Integer type) {

            if (type == 0) {
              /*  if(baseTask.getWorksNum()==3){
                    throw new Exception("很抱歉！作品已上传3次！若还是不满意，请去申诉！");
                }*/
                baseTask.setWorksStatus(0);
                taskDto.save(baseTask);

            } else {
                baseTask.setWorksStatus(2);
                taskDto.save(baseTask);
            }

    }


    //取消任务
    @Override
    public void cncelTask(BaseTask baseTask, Long companyId) throws Exception {

            if (baseTask.getStatus() == 0) {
                //根据任务编号查询任务
                BaseTask ta = taskDto.findByTaskNumber(baseTask.getTaskNumber());
                ta.setStatus(3);
                taskDto.save(ta);
                BaseUserInfo baseUserInfo = FeignServiceMapping.taskUserService.findById(companyId).getBaseUserInfo();
                //获取账户金额
                BigDecimal total = baseUserInfo.getTotalMoney();
                //任务金额
                BigDecimal taskMoney = ta.getTaskMoney();
                //设置账户现在金额
                baseUserInfo.setTotalMoney(total.add(taskMoney));
                baseUserInfo.setFreezingMoney(baseUserInfo.getFreezingMoney().subtract(taskMoney));
                //保存
                FeignServiceMapping.taskUserService.save(baseUserInfo);

                //记录取消任务
        /*        BaseLogTask logTask = new BaseLogTask();
                logTask.setTaskNumber(ta.getTaskNumber());
                logTask.setUserId(baseUserInfo.getId());
                logTask.setTaskName(ta.getTaskName());
                logTask.setType(1);
                logTask.setStatus(1);
                logTask.setCurrentMoney("+" + ta.getTaskMoney().toString());
                logTask.setOpT(new Timestamp(new Date().getTime()));
                logTaskDto.save(logTask);*/
                BaseLogUser baseLogUser = new BaseLogUser();
                baseLogUser.setMoney(baseTask.getTaskMoney());
                baseLogUser.setUserId(baseUserInfo.getId());
                baseLogUser.setUserType(baseUserInfo.getUserType());
                baseLogUser.setType(4);
                baseLogUser.setEqu("任务已取消");
                baseLogUser.setAddTime(new Timestamp(new Date().getTime()));
                FeignServiceMapping.logPayUserService.save(baseLogUser);
            } else {
                throw new Exception("任务被接受,无法取消!");
            }

    }

    @Override
    public Map<String, Long> countTask(Long id) {
        Map<String, Long> map = new HashMap<>();
        Long a = taskDto.aTask(id);
        Long b = taskDto.bTask(id);
        Long c = taskDto.cTask(id);
        Long d = taskDto.dTask(id);
        map.put("0", a);
        map.put("1", b);
        map.put("2", c);
        map.put("3", d);
        return map;
    }

    //网红统计数量
    @Override
    public Map<String, Long> countKolTask(Long id) {
        Map<String, Long> map = new HashMap<>();
        Long a = taskDto.eTask(id);
        Long b = taskDto.xTask(id);
        Long c = taskDto.yTask(id);
        Long d = taskDto.zTask(id);
        map.put("0", a);
        map.put("1", b);
        map.put("2", c);
        map.put("3", d);
        return map;
    }

    //结算任务
    @Override
    public void companyStausTask(BaseTask task) throws Exception {

           /* BaseTask task = taskDto.findByCompanyIdAndKolId(companyId, kolId);
            task.setStatus(3);
            taskDto.save(task);*/
           if(task.getCompanyId()==null||task.getKolId()==null){
               throw new Exception("不符合结算的标准！请查看任务");
           }
           if(task.getWorksStatus()==2&&task.getStatus()==1){
               BaseUserInfo companyUser = FeignServiceMapping.taskUserService.findById(task.getCompanyId()).getBaseUserInfo();
               //任务完成,设置企业总金额和冻结金额
               companyUser.setTotalMoney(companyUser.getTotalMoney().divide(task.getTaskMoney()));
               companyUser.setFreezingMoney(companyUser.getFreezingMoney().divide(task.getTaskMoney()));
               FeignServiceMapping.taskUserService.save(companyUser);
               //任务完成设置网红总金额,和累计金额
               BaseUserInfo kolUser = FeignServiceMapping.taskUserService.findById(task.getKolId()).getBaseUserInfo();

               kolUser.setTotalMoney(kolUser.getTotalMoney().add(task.getTaskMoney().multiply(new BigDecimal(0.9))));
               kolUser.setTotalCashMoney(kolUser.getTotalCashMoney().add(task.getTaskMoney().multiply(new BigDecimal(0.9))));
               FeignServiceMapping.taskUserService.save(kolUser);
               task.setStatus(2);
               taskDto.save(task);
           }else {
               throw new Exception("不符合结算的标准！请查看任务");
           }
    }



    //用户添加竞价
    @Override
    public void add(BaseCompetePrice baseCompetePrice) {
        competePriceDto.save(baseCompetePrice);
    }

    //竞价修改
    @Override
    public void update(BaseCompetePrice baseCompetePrice, Long id) {
        baseCompetePrice.setId(id);

        competePriceDto.save(baseCompetePrice);

    }


    //分页查询竞价
    @Override
    public UserPageData competeList(int pageNum, int pageSize, Map map) {
        Page<BaseCompetePrice> pageList = competeService.findPage(pageNum, pageSize, map);
        UserPageData userPageData = new UserPageData();
        List<BaseCompetePrice> content = pageList.getContent();
        List<BaseTaskUser> list = new ArrayList();
        Set<Long> set = new HashSet<>();
        for (BaseCompetePrice baseCompetePrice : content) {
            baseCompetePrice.setLookNum(baseCompetePrice.getLookNum() + 1);
            competePriceDto.save(baseCompetePrice);
            Long taskId = baseCompetePrice.getTaskId();
            set.add(taskId);
        }
        for (Long l : set) {
            BaseTaskUser baseTaskUser = new BaseTaskUser();
            BaseTask baseTask = taskDto.findById(l).get();
            BaseCompanyUser baseCompanyUser = FeignServiceMapping.taskCompanyService.findById(baseTask.getCompanyId());
            baseTaskUser.setBaseCompanyUser(baseCompanyUser);
            baseTaskUser.setBaseTask(baseTask);
            list.add(baseTaskUser);
        }

        userPageData.list = list;
        userPageData.rows = list.size();
        return userPageData;
    }

    //修改状态
    @Override
    public BaseCompetePrice updateState(Long id, Long companyId) throws Exception {
        Optional<BaseCompetePrice> byId = competePriceDto.findById(id);
        if (byId.isPresent()) {
            BaseCompetePrice baseCompetePrice = byId.get();
            BaseUserInfo userInfo = FeignServiceMapping.taskUserService.findById(companyId).getBaseUserInfo();

            if (baseCompetePrice.getPrice().subtract(new BigDecimal(10)).compareTo(userInfo.getTotalMoney()) < 0) {
                throw new Exception("余额不足！");
            }
            baseCompetePrice.setStatus(1);
            return competePriceDto.save(baseCompetePrice);
        } else {
            throw new Exception("系统错误！");
        }
    }

    //是否推广进入
    @Override
    public BaseTaskUser getType(Long type, Long taskId) throws Exception {
        Optional<BaseTask> byId1 = taskDto.findById(taskId);
        BaseTaskUser baseTaskUser = new BaseTaskUser();

        if (!byId1.isPresent()) {
            throw new Exception("系统异常");
        }
        BaseTask baseTask = byId1.get();

        BaseCompanyUser baseCompanyUser = FeignServiceMapping.taskCompanyService.findById(baseTask.getCompanyId());
        if (type != 0) {
            Optional<BaseCompetePrice> byId = competePriceDto.findById(type);
            if (byId.isPresent()) {
                BaseCompetePrice baseCompetePrice = byId.get();
                BaseUserInfo userInfo = FeignServiceMapping.taskUserService.findById(baseTask.getCompanyId()).getBaseUserInfo();
                if (userInfo.getTotalMoney().compareTo(baseCompetePrice.getPrice()) <= 0) {
                    userInfo.setTotalMoney(new BigDecimal(0));
                    FeignServiceMapping.taskUserService.save(userInfo);
                    baseCompetePrice.setStatus(0);
                    baseCompetePrice.setNumTd(baseCompetePrice.getNumTd() + 1);
                    competePriceDto.save(baseCompetePrice);
                    baseTaskUser.setBaseTask(baseTask);
                    baseTaskUser.setBaseCompanyUser(baseCompanyUser);
                    return baseTaskUser;
                }
                if (baseCompetePrice.getPrice().compareTo(baseCompetePrice.getMaxPrice().subtract(baseCompetePrice.getCostPrice())) <= 0) {
                    userInfo.setTotalMoney(userInfo.getTotalMoney().subtract(baseCompetePrice.getPrice()));
                    FeignServiceMapping.taskUserService.save(userInfo);
                    baseCompetePrice.setStatus(0);
                    baseCompetePrice.setCostPrice(baseCompetePrice.getPrice().add(baseCompetePrice.getCostPrice()));
                    baseCompetePrice.setNumTd(baseCompetePrice.getNumTd() + 1);
                    competePriceDto.save(baseCompetePrice);
                    baseTaskUser.setBaseTask(baseTask);
                    baseTaskUser.setBaseCompanyUser(baseCompanyUser);
                    return baseTaskUser;
                }
            } else {

                throw new Exception("系统异常");
            }
        }

        baseTaskUser.setBaseTask(baseTask);
        baseTaskUser.setBaseCompanyUser(baseCompanyUser);
        return baseTaskUser;

    }
}
